package com.xyzwps.ewa.modules.auth.password

import com.xyzwps.ewa.data.database
import com.xyzwps.ewa.modules.user.UserId
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.transactions.transaction

object PasswordRepository {

    object PasswordTable : Table() {
        val userId = long("userId")
        val encrypted = varchar("encrypted", length = 200)
        override val primaryKey = PrimaryKey(userId)
    }

    init {
        transaction {
            SchemaUtils.create(PasswordTable)
        }
    }

    fun create(password: Password) {
        PasswordTable.insert {
            it[userId] = password.userId.value
            it[encrypted] = password.encrypted
        }
    }

    fun read(userId: UserId): Password? = PasswordTable.selectAll()
        .where { PasswordTable.userId eq userId.value }
        .map { Password(UserId(it[PasswordTable.userId]), it[PasswordTable.encrypted]) }
        .singleOrNull()

    fun update(password: Password) {
        PasswordTable.update({ PasswordTable.userId eq password.userId.value }) {
            it[encrypted] = password.encrypted
        }
    }
}